package com.sky.utils;

import cn.hutool.core.util.StrUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sky.exception.OrderBusinessException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

// @SpringBootTest
@Component
@Slf4j
public class CheckRange {

    private static final String shopAddress = "北京市海淀区上地十街10号";
    // private static final String shopAddress = "北京市市辖区海淀区";

    private static final String ak = "wQtpkTKt2rFMQoll23D9X8NcXJYLN62s";

    // private static final String tempUrl = "北京市海淀区上地十街11号";

    public void checkRange(String userUrl) {
        checkOutOfRange(userUrl);
    }

    // @Test
    // public void mainTest() {
    //     checkOutOfRange(tempUrl);
    // }

    private void checkOutOfRange(String address) {
        JSONObject shopLocation = getLocation(shopAddress);
        JSONObject userLocation = getLocation(address);

        String shopLat = shopLocation.getStr("lat");
        String shopLng = shopLocation.getStr("lng");
        String userLat = userLocation.getStr("lat");
        String userLng = userLocation.getStr("lng");

        int distance = getDistance(shopLat + "," + shopLng, userLat + "," + userLng);

        log.info("饭店地址: {}", shopAddress);
        log.info("用户地址: {}", address);
        log.info("饭店经纬度: {}", shopLocation);
        log.info("用户经纬度: {}", userLocation);

        if (distance > 10000) {
            throw new OrderBusinessException("超出配送范围");
        }

        log.info("配送距离: {}米", distance);
    }

    private JSONObject getLocation(String address) {
        String geoUrl = StrUtil.format("https://api.map.baidu.com/geocoding/v3?address={}&output=json&ak={}", address, ak);
        String response = HttpRequest.get(geoUrl).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(response);
        if (!"0".equals(jsonObject.getStr("status"))) {
            throw new OrderBusinessException("地址解析失败");
        }
        return jsonObject.getJSONObject("result").getJSONObject("location");
    }

    private int getDistance(String origin, String destination) {
        String directionUrl = StrUtil.format("https://api.map.baidu.com/directionlite/v1/driving?origin={}&destination={}&ak={}", origin, destination, ak);
        String result = HttpRequest.get(directionUrl).execute().body();
        JSONObject jsonObject = JSONUtil.parseObj(result);
        if (!"0".equals(jsonObject.getStr("status"))) {
            throw new OrderBusinessException("配送路线规划失败");
        }
        JSONObject route = jsonObject.getJSONObject("result").getJSONArray("routes").getJSONObject(0);
        return route.getInt("distance");
    }

}